<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
error_reporting(0);
header('Content-Type: text/html; charset=utf-8');

class Users extends CI_Controller {
    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url');
        $this->load->helper('form');
        $this->load->helper('html');
        $this->load->helper('cookie');
        $this->load->library('session');
        $this->load->model('users_model');
        $this->load->model('crud_model');
        $this->load->library('../controllers/crud');
        $this->load->library('email');
        $this->load->helper('captcha');
    }

    public function checkEmail()
    {
        $email = $this->input->post('email');
        $checkEmail = $this->users_model->getEmail($email);
        echo $checkEmail;
    }

	public function createNewUser()
	{
        $email = $this->input->post('email');
        $password = md5($this->input->post('password'));
        $sex = $this->input->post('sex');
        $name = $this->input->post('name');
        $phone = $this->input->post('phone');

        $day = $this->input->post('day');
        $month = $this->input->post('month');
        $year = $this->input->post('year');
        $birth = mktime(0,0,0, $month, $day, $year);
        $birthday = date("Y-m-d H:i:s", $birth);

        $dt = date("Y-m-d H:i:s");
        $expired_active = date( "Y-m-d H:i:s", strtotime( "$dt +2 day" ) ); //cong them 2 ngay

        $checkEmail = $this->users_model->getEmail($email);
        if($checkEmail != 0){
            echo '1';
        }
        else{
            $confirm_code=md5(uniqid(rand()));
            $this->users_model->insert($email, $password, $sex, $name, $phone, $birthday, $confirm_code, $expired_active);
            echo $confirm_code;
        }
    }

    public function checkLogin()
    {
        $email = $this->input->post('email');
        $password = md5($this->input->post('password'));
        $remember = $this->input->post('remember');

        $field = "active";
        $active = $this->users_model->getInfoUser($field, $email);
        $checkEmail = $this->users_model->getEmail($email);
        $checkLogin = $this->users_model->getLoginInfo($email, $password);
        $checkAdminLogin = $this->users_model->getAdminLoginInfo($email, $password);
        $linkAdmin = $this->session->userdata('linkAdmin');
        if($checkEmail == 0){
            echo "000";
        }
        else{
            if($active == 0){
                echo "00";
            }
            else{
                if($linkAdmin == ''){
                    if($checkLogin != 0){
                        if($remember == 1){
                            $this->storeSession($email);
                            $this->session->set_userdata('new_expiration',1209600); //2 weeks
                            $this->session->sess_update(); //force the session to update the cookie and/or database
                        }
                        $this->setInfoLogin($email);
                    }
                    else{
                        echo "0";
                    }
                }
                else{
                    if($checkAdminLogin != 0){
                        if($remember == 1){
                            $this->storeSession($email);
                            $this->session->set_userdata('new_expiration',1209600); //2 weeks
                            $this->session->sess_update(); //force the session to update the cookie and/or database
                        }
                        $this->setInfoLogin($email);
                    }
                    else{
                        echo "0";
                    }
                }
            }
        }
    }

    public function setEmptyAdminLink()
    {
        $this->session->set_userdata('linkAdmin', '');
    }

    public function setInfoLogin($email)
    {
        $this->session->set_userdata('email', $email);
        $field1 = 'name';
        $name = $this->users_model->getInfoUser($field1, $email);
        $this->session->set_userdata('name', $name);

        $field2 = 'admin';
        $admin = $this->users_model->getInfoUser($field2, $email);
        $this->session->set_userdata('isAdmin', $admin);
    }

    public function storeSession($email){
        $session_id = $this->session->userdata('session_id');
        $ip_address = $this->session->userdata('ip_address');
        $user_agent = $this->session->userdata('user_agent');
        $last_activity = $this->session->userdata('last_activity');
        $user_data = $email;

        $data = array(
            'session_id' => $session_id,
            'ip_address' => $ip_address,
            'user_agent' => $user_agent,
            'last_activity' => $last_activity,
            'user_data' => $user_data
        );
        $this->crud_model->insert('ci_sessions', $data);
    }

    //send mail confirm register account
    public function sendMailRegister() {
        $date = date("d-m-Y");

        $email = $this->input->post('email');
        $name = $this->input->post('name');
        $password = $this->input->post('password');
        $key = $this->input->post('key');

        $data = array(
            'email' => $email,
            'name' => $name,
            'password' => $password,
            'key' => $key,
            'date' => $date
        );

        $result = $this->crud->subscribe($email, "Xác nhận đăng ký tài khoản", 'mail/register', $data);
        echo $result;
    }

    public function viewEmail(){
        $this->load->view('head');
        $this->load->view('mail/register');
    }

    public function active(){
        $this->load->view('head');
        $this->load->view('register/active_fail');
    }

    public function confirm(){
        $now = date("Y-m-d H:i:s");
        $key = $this->input->get('key', true);
        $field = "expired_active";
        $expired_active = $this->users_model->getExpiredActive($field, $key);
        $num = $this->users_model->getConfirmCode($key);
        if($now > $expired_active || $num == 0){
            $this->load->view('head');
            $this->load->view('register/active_fail');
        }
        else{
            $query = $this->users_model->confirm($key, $now);
            if($query == 0){
                $this->load->view('head');
                $this->load->view('register/active_success');
            }
            else{
                $this->load->view('head');
                $this->load->view('register/active_fail');
            }
        }
    }

    public function reActiveView()
    {
        $data['captcha'] = $this->getCaptcha();
        $this->load->view('head');
        $this->load->view('register/reactive_view', $data);
    }

    public function reactiveRegister(){
        $captcha = $this->input->post('captcha', true);
        $captchaSystem = $this->session->userdata('captcha');
        if($captcha != $captchaSystem){
            echo '2';
        }
        else{
            $email = $this->input->post('email', true);
            $num = $this->users_model->getEmail($email);
            if($num == 0){
                echo '0';
            }
            else{
                $dt = date("Y-m-d H:i:s");
                $expired_active = date( "Y-m-d H:i:s", strtotime( "$dt +2 day" ) ); //cong them 2 ngay
                $this->users_model->updateExpiredActive($email, $expired_active);

                $field = "confirm_code";
                $key = $this->users_model->getInfoUser($field, $email);

                $data = array(
                    'email' => $email,
                    'key' => $key
                );
                $result = $this->crud->subscribe($email, "Kích hoạt tài khoản", "mail/reactive", $data);
                if($result == 0){
                    echo '1';
                }
                else{
                    echo $result;
                }
            }
        }
    }

    public function checkEmailFP(){
        $captcha = $this->input->post('captcha', true);
        $captchaSystem = $this->session->userdata('captcha');
        if($captcha != $captchaSystem){
            echo 2;
        }
        else{
            $email = $this->input->post('email', true);
            $data = $this->users_model->find($email);
            if($data == 0){
                echo 0;
            }
            else{
                $condition = array(
                    'step1' => true,
                    'emailFP' => $email
                );
                $this->session->set_userdata($condition);
                echo 1;
            }
        }
    }

    public function inputEmail()
    {
        $data['captcha'] = $this->getCaptcha();
        $data['email'] = $this->input->get('email', true);
        $this->load->view('head');
        $this->load->view('login/input_email', $data);
    }

    public function chooseMethod(){
        $data['email'] = $this->session->userdata('emailFP');
        $field = "phone";
        $phone = $this->users_model->getInfoUser($field, $data['email']);
        $phoneSubStr1 = substr($phone, 0, strlen($phone)-2);
        $phoneSubStr2 = substr($phone, strlen($phone)-2, strlen($phone));
        $phoneReplace = preg_replace('/[0-9]/', '*', $phoneSubStr1);
        $phoneAfter = $phoneReplace.$phoneSubStr2;
        $data['fone'] = $phone;
        $data['phone'] = $phoneAfter;
        $this->load->view('head');
        $this->load->view('login/choose_method', $data);
    }

    public function sendCode(){
        $email = $this->session->userdata('emailFP');
        $phone = $this->session->userdata('fone');
//        $phoneAfter = settype($phone, "string"); //set kieu du lieu
//        var_dump($phone);
        $fone = substr($phone, 1, strlen($phone)-1);
//        echo $fone;
        $data['email'] = $email;
        $data['phone'] = $phone;
        $method = $this->session->userdata('method');
        $data['method'] = $method;
        $code = mt_rand(100000, 999999); //random 1 chuoi gom 6 ky tu
        $confirm_code = md5(uniqid(rand()));
        $data['code'] = $confirm_code;

        if($method == 0){
            $dt = date("Y-m-d H:i:s");
            $expired_reset = date( "Y-m-d H:i:s", strtotime( "$dt +2 day" ) ); //cong them 2 ngay

            $check = $this->users_model->getPasswordTable($email);
            if($check == 0){
                $table = "password";
                $password = array(
                    'email' => $email,
                    'confirm_code' => $confirm_code,
                    'password_code' => $code,
                    'expired_reset' => $expired_reset
                );
                $query1 = $this->crud_model->insert($table, $password);
                if($query1 != 0){
                    echo $query1;
                }
            }
            else{
                $query2 = $this->users_model->updatePasswordTable($email, $confirm_code, $code, $expired_reset);
                if($query2 != 0){
                    echo $query2;
                }
            }
            $this->subscribe4($email, $code, $confirm_code);
        }
        else{
            $dt = date("Y-m-d H:i:s");
            $expired_reset = date( "Y-m-d H:i:s", strtotime( "$dt +2 day" ) ); //cong them 2 ngay

            $check = $this->users_model->getPasswordTable($email);
            if($check == 0){
                $table = "password";
                $password = array(
                    'email' => $email,
                    'confirm_code' => $confirm_code,
                    'password_code' => $code,
                    'expired_reset' => $expired_reset
                );
                $query1 = $this->crud_model->insert($table, $password);
                if($query1 != 0){
                    echo $query1;
                }
            }
            else{
                $query2 = $this->users_model->updatePasswordTable($email, $confirm_code, $code, $expired_reset);
                if($query2 != 0){
                    echo $query2;
                }
            }
            $this->sendSMS($fone, $code);
            $sms = $this->session->userdata('sms');
            if($sms != 0){
                echo $sms;
            }
        }
        $this->load->view('head');
        $this->load->view('login/input_code', $data);
    }

    public function checkCode()
    {
        $code = $this->input->post('code', true);
        $key = $this->input->post('key', true);
        $check = $this->users_model->checkCode($code, $key);
        if($check == 0){
            echo 0;
        }
        else{
            $condition = array(
                'step2' => false,
                'emailFP' => '',
                'sms' => '',
                'fone' => ''
            );
            $this->session->set_userdata($condition);
            echo 1;
        }
    }

    public function sendEmailSocial(){
        $email = $this->input->post('email', true);
        $num = $this->users_model->getEmail($email);
        if($num == 0){
            echo 0;
        }
        else{
            $this->subscribe2($email);
        }
    }

    //send mail request a new password
    public function subscribe2($email) {
        $data = array(
            'email' => $email
        );

        $data['site_name'] = 'AUTOZONEVN';

        $this->sendEmail2($email, $data);
    }

    public function sendEmail2($email, $data) {
        $config = Array(
            'protocol' => 'smtp',
            'smtp_host' => 'ssl://smtp.googlemail.com',
            'smtp_port' => 465,
            'smtp_user' => '',
            'smtp_pass' => '',
            'mailtype' => 'html', //neu van ko hien thi trong body mail thi set lai trong file libraries/email
            'charset' => 'iso-8859-1',
            'wordwrap' => TRUE
        );
        $this->load->library('email', $config);

        $this->email->set_newline("\r\n");

        $this->email->from('huanluyen.auto@gmail.com', 'www.cuutinhxalo.com');
        $this->email->to($email);
        $this->email->subject('Yêu cầu cài đặt mật khẩu mới cho tài khoản AUTOZONEVN');
        $body = $this->load->view('register/reset_password', $data, TRUE);
        $this->email->message($body);

        $result = $this->email->send();

        if (!$result){
            $this->email->print_debugger();
        }
        else{
            echo "1";
        }
    }

    //change password
    public function resetPassword()
    {
        $date = date("H:i:s d-m-Y");

        $email = $this->input->post('email');
        $oldPass = $this->input->post('oldPass');
        $oldPassEncript = md5($oldPass);
        $newPass = $this->input->post('newPass');
        $newPassEncript = md5($newPass);

        $num = $this->users_model->getLoginInfo($email, $oldPassEncript);
        if($num == 0){
            echo 0;
        }
        else{
            $query = $this->users_model->updatePassword($email, $newPassEncript);
            if($query != 0){
                echo $query;
            }

            $this->subscribe3($email, $newPass, $date);
        }
    }

    //send mail reactive account
    public function subscribe3($email, $newPass, $date) {
        $data = array(
            'email' => $email,
            'password' => $newPass,
            'date' => $date
        );

        $data['site_name'] = 'AUTOZONEVN';

        $this->sendEmail3($email, $data);
    }

    public function sendEmail3($email, $data) {
        $config = Array(
            'protocol' => 'smtp',
            'smtp_host' => 'ssl://smtp.googlemail.com',
            'smtp_port' => 465,
            'smtp_user' => '',
            'smtp_pass' => '',
            'mailtype' => 'html', //neu van ko hien thi trong body mail thi set lai trong file libraries/email
            'charset' => 'iso-8859-1',
            'wordwrap' => TRUE
        );
        $this->load->library('email', $config);

        $this->email->set_newline("\r\n");

        $this->email->from('huanluyen.auto@gmail.com', 'www.cuutinhxalo.com');
        $this->email->to($email);
        $this->email->subject('Thay đổi mật khẩu');
        $body = $this->load->view('login/email_password', $data, TRUE);
        $this->email->message($body);

        $result = $this->email->send();

        if (!$result){
            $this->email->print_debugger();
        }
        else{
            echo "1";
        }
    }

    //send mail request a code
    public function subscribe4($email, $code, $key) {
        $data = array(
            'email' => $email,
            'code' => $code,
            'key' => $key
        );

        $data['site_name'] = 'AUTOZONEVN';

        $this->sendEmail4($email, $data);
    }

    public function sendEmail4($email, $data) {
        $config = Array(
            'protocol' => 'smtp',
            'smtp_host' => 'ssl://smtp.googlemail.com',
            'smtp_port' => 465,
            'smtp_user' => '',
            'smtp_pass' => '',
            'mailtype' => 'html', //neu van ko hien thi trong body mail thi set lai trong file libraries/email
            'charset' => 'iso-8859-1',
            'wordwrap' => TRUE
        );
        $this->load->library('email', $config);

        $this->email->set_newline("\r\n");

        $this->email->from('huanluyen.auto@gmail.com', 'www.cuutinhxalo.com');
        $this->email->to($email);
        $this->email->subject('Yêu cầu cài đặt mật khẩu mới cho tài khoản AUTOZONEVN');
        $body = $this->load->view('login/email_code', $data, TRUE);
        $this->email->message($body);

        $result = $this->email->send();

        if (!$result){
            $this->email->print_debugger();
        }
    }

    public function changePassword()
    {
        $dt = date("Y-m-d H:i:s");
        $key = $this->input->get('key', true);

        $field = "expired_reset";
        $check2 = $this->users_model->getInfoPassword($field, $key);

        $check1 = $this->users_model->checkConfirmCode($key);
        if($check1 == 0 || $check2 == '' || $check2 <= $dt){
            header("Location: ".base_url()."password/error");
        }
        else{
            $email = $this->input->get('email', true);
            $data['email'] = $email;
            $data['key'] = $key;
            $this->load->view('head');
            $this->load->view('login/input_password', $data);
        }
    }

    public function changePasswordError()
    {
        $this->load->view('head');
        $this->load->view('login/password_error');
    }

    public function updatePassword()
    {
        $dt = date("Y-m-d H:i:s");
        $newPass = $this->input->post('newPass', true);
        $newPassEncript = md5($newPass);
        $key = $this->input->post('key', true);
        $field = "email";
        $email = $this->users_model->getInfoPassword($field, $key);

        $query1 = $this->users_model->updateChangedPasswordTime($dt, $key);
        if($query1 != 0){
            echo $query1;
        }

        $query = $this->users_model->updatePassword($email, $newPassEncript);
        if($query != 0){
            echo $query;
        }
        else{
            echo 1;
        }
    }

    public function setStep2FP(){
        $this->session->set_userdata('step2', true);
        $fone = $this->input->post('fone');
        $method = $this->input->post('method');

        $data = array(
            'step1' => false,
            'step2' => true,
            'fone' => $fone,
            'method' => $method
        );

        $this->session->set_userdata($data);
        echo $this->session->userdata('step2').' '.$this->session->userdata('fone').' '.$this->session->userdata('method');
    }

    public function checkAdmin()
    {
        $email = $this->session->userdat('email');
        $field = "admin";
        $isAdmin = $this->users_model->getInfoUser($field, $email);
        echo $isAdmin;
    }

    public function login()
    {
        $ip = $this->session->userdata('ip_address');
        $check = $this->users_model->getSessionTable($ip);
        $isLogin = $this->session->userdata('email');
        if($check != 0){
            $field= "user_data";
            $email = $this->users_model->getEmailSessionTable($field, $ip);
            $this->session->set_userdata('email', $email);
            $field2 = 'admin';
            $admin = $this->users_model->getInfoUser($field2, $email);
            $this->session->set_userdata('isAdmin', $admin);
            $this->session->set_userdata('new_expiration',1209600); //2 weeks
            $this->session->sess_update(); //force the session to update the cookie and/or database
            header("location:javascript://history.go(-1)");
        }
        else if($isLogin != ''){
            $email = $isLogin;
            $this->session->set_userdata('email', $email);
            $field2 = 'admin';
            $admin = $this->users_model->getInfoUser($field2, $email);
            $this->session->set_userdata('isAdmin', $admin);
            header("location:javascript://history.go(-1)");
        }
        else{
            $this->load->view('head');
            $this->load->view('login');
        }
    }

    public function register()
    {
        $this->load->view('head');
        $this->load->view('header');
        $this->load->view('navbar');
        $this->load->view('register');
        $this->load->view('footer');
    }

    public function logOut()
    {
        $ip = $this->session->userdata('ip_address');
        $check = $this->users_model->getSessionTable($ip);
        if($check != ''){
            $this->crud_model->delete('ip_address', $ip, 'ci_sessions');
        }
        $this->session->sess_destroy();
        redirect(base_url());
    }

    public function getIDUser(){
        $email = $this->session->userdata('email');
        $field = 'id';
        $idUser = $this->users_model->getInfoUser($field, $email);
        return $idUser;
    }

    public function sendSMS($number, $code)
    {
        require "twilio-php/Services/Twilio.php";

        $sid = "AC49327e8286de742a35d76572832aee5d";
        $token = "c6ff3fefee6d174879013b4e1bf4ed3a";
        $client = new Services_Twilio($sid, $token);
        try{
            $client->account->messages->sendMessage("+12512723033", "+84".$number, $code);
            $this->session->set_userdata("sms", 0);
        } catch (Services_Twilio_RestException $e) {
            $this->session->set_userdata("sms", $e->getMessage());
        }

//        print $message->sid;
    }

    public function getCaptcha($i = 0)
    {
        $vals = array(
            'img_path'	=> './assets/images/captcha/',
            'img_url'	=> base_url().'assets/images/captcha/',
            'font_path'	=> './system/fonts/texb.ttf',
            'img_width'	=> '150',
            'img_height' => 30,
            'expiration' => 7200
        );

        $cap = create_captcha($vals);
        $this->session->set_userdata('captcha', $cap['word']);
        if($i == 1){
            echo $cap['image'];
        }
        return $cap['image'];
    }
}